package com.xxs.controller.admin;

import java.io.File;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;

import com.jfinal.aop.Before;
import com.jfinal.core.JFinal;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;
import com.xxs.interceptor.AdminInterceptor;
import com.xxs.utils.UUIDUtils;
import com.xxs.utils.xml.Fields;
import com.xxs.utils.xml.XmlDom4jUtils;

@Before(AdminInterceptor.class)
@SuppressWarnings("unchecked")
public class InfoController extends BaseAdminSiteController {
	public void list(){
		String nodeId = getPara(0);
		String modelInfoId = getPara(1);
		if(nodeId==null){
			nodeId = getSessionAttr("nodeId");
			modelInfoId = getSessionAttr("modelInfoId");
		}
		List<Element> list = XmlDom4jUtils.getElementsByAttrAndValue(getXmlPath(getCurrentSiteCode(), "info"), "info", "nodeId", nodeId);
		setAttr("fieldList", XmlDom4jUtils.getFieldsByAttrAndValue(getXmlPath(getCurrentSiteCode(), "model"),"info","id",modelInfoId));
    	setAttr("list", list);
    	setAttr("nodeId", nodeId);
    	setAttr("modelInfoId", modelInfoId);
    	setAttr("modelName", getAttrForStr("modelName"));
    	render("list.html");
    }
	public void add(){
		String nodeId = getPara(0);
		String modelInfoId = getPara(1);
		if(modelInfoId == null){
			renderText("添加前请选择内容分类，内容分类ID为空");
		}
		Document document = XmlDom4jUtils.getDocument(getXmlPath(getCurrentSiteCode(),"model"));
		Element element = null;
    	List<Element> listElements = document.selectNodes("//info[@id='"+modelInfoId+"']");
    	if(listElements!=null && listElements.size()>0){
    		element = listElements.get(0);
    	}
    	setAttr("fieldList", XmlDom4jUtils.getFields(element));
    	setAttr("nodeId", nodeId);
    	setAttr("modelInfoId", modelInfoId);
		render("add.html");
	}
	public void save(){
		String nodeId = getPara(0);
		String modelInfoId = getPara(1);
		String modelName = getModeName();
		String siteCode = getCurrentSiteCode();
		//获取fieldList  用于完全保存
		Document document1 = XmlDom4jUtils.getDocument(getXmlPath(siteCode, "model"));
		Element element1 = null;
    	List<Element> listElements = document1.selectNodes("//info[@id='"+modelInfoId+"']");
    	if(listElements!=null && listElements.size()>0){
    		element1 = listElements.get(0);
    	}
    	List<Fields> fieldList = XmlDom4jUtils.getFields(element1);
		//获取要保存的document对象
		Document document = XmlDom4jUtils.getDocument(getXmlPath(siteCode, modelName));
		Element element = document.getRootElement();
		Element newElement = element.addElement(modelName);
		newElement.setName(modelName);
		for (int i = 0; i < fieldList.size(); i++) {
			System.out.println("当前循环的属性名："+fieldList.get(i).getName()+"填充的内容"+getPara(fieldList.get(i).getName()));
			if("id".equals(fieldList.get(i).getName())){
				newElement.addAttribute(fieldList.get(i).getName(), UUIDUtils.creatUUID());
			}else{
				newElement.addAttribute(fieldList.get(i).getName(), getPara(fieldList.get(i).getName()));
			}
		}
		//手动添加nodeId和modelInfoId，便于修改操作
		newElement.addAttribute("nodeId", nodeId);
		newElement.addAttribute("modelInfoId", modelInfoId);
		
		try {
			XmlDom4jUtils.saveDocumentToFile(getXmlPath(siteCode, modelName), document);
		} catch (Exception e) {
			e.printStackTrace();
		}
		list();
	}
	public void edit(){
		String nodeId = getPara(0);
		String modelInfoId = getPara(1);
		String id = getPara(2);
		String modelName = getModeName();
		Element element = null;
		List<Element> listElements = XmlDom4jUtils.getElementsByAttrAndValue(getXmlPath(getCurrentSiteCode(), modelName), modelName, "id", id);
		if(listElements!=null && listElements.size()>0){
			element = listElements.get(0);
		}
		//获取到modelInfo中配置的Info模型所含有的字段
		setAttr("fieldList", XmlDom4jUtils.getFieldsByAttrAndValue(getXmlPath(getCurrentSiteCode(), "model"),"info","id",modelInfoId));
		setAttr("id", id);
		setAttr("nodeId", nodeId);
		setAttr("modelInfoId", modelInfoId);
		setAttr("element", element);
		render("edit.html");
	}
	public void update(){
		String id = getPara(2);
		String modelName = getModeName();
		String siteCode = getCurrentSiteCode();
		Element element = null;
    	Document document = XmlDom4jUtils.getDocument(getXmlPath(siteCode, modelName));
    	List<Element> listElements = document.selectNodes("//"+modelName+"[@id='"+id+"']");
    	if(listElements!=null && listElements.size()>0){
    		element = listElements.get(0);
    		Enumeration<String> enumeration = getParaNames();
        	while(enumeration.hasMoreElements()){
        		String name=(String)enumeration.nextElement();
        		String value=getPara(name);
        		System.out.print(name + "=" + value);
        		Attribute attribute = element.attribute(name);  
        		if(attribute==null){
        			element.addAttribute(name, value);
        		}else{
        			attribute.setValue(value);
        		}
        	}
        	try {
        		XmlDom4jUtils.saveDocumentToFile(getXmlPath(siteCode, modelName), document);
        	} catch (Exception e) {
        		e.printStackTrace();
        	}
    	}
    	list();
    }
	/**
	 * 文件上传
	 */
	public void editor(){
		String rootPath = JFinal.me().getContextPath();
		String siteCode = getCurrentSiteCode();
		try {
			String uploadPath = rootPath + "\\db\\"+siteCode+"\\front\\_files\\upload\\";
			System.out.println("uploadPath:"+uploadPath);
			File filepath = new File(uploadPath);
			if(!filepath.exists()){
				filepath.mkdirs();
			}
			UploadFile file = getFile();
			System.out.println(file.getUploadPath());
//            User user = WebUtils.currentUser(this);
//            if (null == user) {
//                setAttr("error", 1);
//                setAttr("message", "上传出错，请先登陆！");
//                render(new JsonRender(new String[]{"error", "message"}).forIE());
//                return;
//            }
			//String type = getPara("dir"); //辨别 图片，zip，电影以及其他，自己不想去折腾了
			String fileName = file.getFileName();
			String fileType = getFileType(fileName);
			String newName = System.currentTimeMillis() + fileType;
			// 第一次上传文件
			String filePath = uploadPath + newName;
			System.out.println("0000:"+PathKit.getWebRootPath()+filePath);
			// 删除本地临时文件
			file.getFile().renameTo(new File(PathKit.getWebRootPath()+filePath));
//            getResponse().getWriter().write(filePath);
			renderText(filePath);
		} catch (Exception e) {
			e.getMessage();
			renderText("图片上传错误，请联系管理员");
		}
	}
	/**
	 * 编辑器图片上传
	 */
    public void uploadImage(){
        String rootPath = JFinal.me().getContextPath();
        String siteCode = getCurrentSiteCode();
        try {
        	String uploadPath = rootPath + "\\db\\"+siteCode+"\\front\\_files\\upload\\";
        	System.out.println("uploadPath:"+uploadPath);
        	File filepath = new File(uploadPath);
        	if(!filepath.exists()){
        		filepath.mkdirs();
        	}
            UploadFile file = getFile();
            System.out.println(file.getUploadPath());
//            User user = WebUtils.currentUser(this);
//            if (null == user) {
//                setAttr("error", 1);
//                setAttr("message", "上传出错，请先登陆！");
//                render(new JsonRender(new String[]{"error", "message"}).forIE());
//                return;
//            }
            //String type = getPara("dir"); //辨别 图片，zip，电影以及其他，自己不想去折腾了
            String fileName = file.getFileName();
            String fileType = getFileType(fileName);
            String newName = System.currentTimeMillis() + fileType;
            // 第一次上传文件
            String filePath = uploadPath + newName;
            System.out.println("0000:"+PathKit.getWebRootPath()+filePath);
            // 删除本地临时文件
            file.getFile().renameTo(new File(PathKit.getWebRootPath()+filePath));
//            getResponse().getWriter().write(filePath);
            setAttr("code", 0);
            setAttr("msg", "上传成功");
            Map<String, String> map = new HashMap<String, String>();
            map.put("src", filePath);
            map.put("title", file.getFileName());
            setAttr("data",map);
            renderJson();
        } catch (Exception e) {
        	e.getMessage();
        	setAttr("code", 1);
            setAttr("msg", "上传失败");
            renderJson();
        }
    }

    /**
     * 获取文件类型
     * @param @param fileName
     * @param @return    设定文件
     * @return String    返回类型
     * @throws
     */
    private static String getFileType(String fileName){
        return fileName.substring(fileName.lastIndexOf('.'), fileName.length());
    }
}
